import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.*;

public class NRatingNUser extends Configured implements Tool 
{
	
	public static class Map extends
			Mapper<LongWritable, Text, LongWritable, LongWritable> {

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			StringTokenizer tokenizer = new StringTokenizer(line);
			tokenizer.nextToken();
			context.write(new LongWritable(Long.parseLong((tokenizer.nextToken()))), new LongWritable(1));
		}
	}

	public static class Reduce extends
			Reducer<LongWritable, LongWritable, LongWritable, LongWritable> {
		public void reduce(LongWritable key, Iterable<LongWritable> values,
				Context context) throws IOException, InterruptedException {
			Long sum = 0L;
			for (LongWritable val : values) {
				sum = sum + val.get();
			}
			context.write(key, new LongWritable(sum));
		}
	}

	public int run(String[] args) throws Exception {
		/* 
		 * Calculate ratings per article
		 */
		Job job = new Job(getConf());
		job.setJarByClass(NRatingNUser.class);
		job.setJobName("NRatingNUser");

		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(LongWritable.class);

		job.setMapperClass(Map.class);
		job.setCombinerClass(Reduce.class);
		job.setReducerClass(Reduce.class);

		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		boolean success = job.waitForCompletion(true);
		return success ? 0 : 1;
	}

	 
	 public static void main(String[] args) throws Exception {
		int ret = ToolRunner.run(new NRatingNUser(), args);
		System.exit(ret);
	}

}
